const UserLog = require('../models/UserLog');
const db = require('../config/database');

const getAllUserLogs = async (req, res) => {
  try {
    const result = await UserLog.getAll(req.query);
    res.json({
      success: true,
      data: result.rows,
      total: result.total
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: '获取用户日志失败',
      error: error.message
    });
  }
};

const createUserLog = async (req, res) => {
  try {
    const insertId = await UserLog.create(req.body);
    res.json({ success: true, insertId });
  } catch (error) {
    res.status(500).json({ success: false, message: '新增失败', error: error.message });
  }
};

const updateUserLog = async (req, res) => {
  try {
    const { no } = req.params;
    const ok = await UserLog.update(no, req.body);
    if (ok) {
      res.json({ success: true });
    } else {
      res.status(404).json({ success: false, message: '日志不存在' });
    }
  } catch (error) {
    res.status(500).json({ success: false, message: '更新失败', error: error.message });
  }
};

const deleteUserLog = async (req, res) => {
  try {
    const { no } = req.params;
    const ok = await UserLog.delete(no);
    if (ok) {
      res.json({ success: true });
    } else {
      res.status(404).json({ success: false, message: '日志不存在' });
    }
  } catch (error) {
    res.status(500).json({ success: false, message: '删除失败', error: error.message });
  }
};

const getStats = async (req, res) => {
  try {
    const { start, end } = req.query;
    let sql = `SELECT t.name as tool_name, COUNT(*) as count
      FROM user_log u
      LEFT JOIN lib_tool t ON u.tool_id = t.uuid
      WHERE 1=1`;
    const params = [];
    if (start) { sql += ' AND u.create_at >= ?'; params.push(start); }
    if (end) { sql += ' AND u.create_at <= ?'; params.push(end); }
    sql += ' GROUP BY t.name ORDER BY count DESC';
    console.log('[统计SQL]', sql, params); // 调试输出
    const [rows] = await db.query(sql, params);
    res.json({ success: true, data: rows });
  } catch (error) {
    res.status(500).json({ success: false, message: '统计失败', error: error.message });
  }
};

module.exports = { getAllUserLogs, createUserLog, updateUserLog, deleteUserLog, getStats };